package br.com.atibrasil.fx.aplication;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Date;

import javafx.application.Application;
import javafx.beans.value.*;
import javafx.collections.*;
import javafx.concurrent.*;
import javafx.event.*;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.stage.Stage;
 
public class TaskTest extends Application {
  public static void main(String[] args) throws Exception { launch(args); }
  public void start(final Stage stage) throws Exception {
    final Label statusLabel = new Label("Status");
    final Button runButton = new Button("Run");
    final ListView<String> peopleView = new ListView<String>();
    peopleView.setPrefSize(220, 162);
    final ProgressBar progressBar = new ProgressBar();
    progressBar.prefWidthProperty().bind(peopleView.prefWidthProperty());
 
    runButton.setOnAction(new EventHandler<ActionEvent>() {
      @Override public void handle(ActionEvent actionEvent) {
        final Task task = new Task<ObservableList<String>>() {
          @Override protected ObservableList<String> call() throws InterruptedException {
        	  updateMessage("Finding friends . . .");
        	  for (int i = 0; i < 10; i++) {
	        	  Thread.sleep(200);
	        	  updateProgress(i+1, 10);
        	  }
        	  updateMessage("Finished.");
        	  return FXCollections.observableArrayList("John", "Jim", "Geoff", "Jill", "Suki");
          }
        };
 
        statusLabel.textProperty().bind(task.messageProperty());
        runButton.disableProperty().bind(task.runningProperty());
        peopleView.itemsProperty().bind(task.valueProperty());
        progressBar.progressProperty().bind(task.progressProperty());
        task.stateProperty().addListener(new ChangeListener<Worker.State>() {
          @Override public void changed(ObservableValue<? extends Worker.State> observableValue, Worker.State oldState, Worker.State newState) {
            if (newState == Worker.State.SUCCEEDED) {
              System.out.println("This is ok, this thread " + Thread.currentThread() + " is the JavaFX Application thread.");
              runButton.setText("Voila!");
            }
          }
        });
 
        new Thread(task).start();
      
        /*
        try {
			  Date inicio = new Date();
			  Connection con;
			  Statement stm;			    	
			  String nome = "C:/ATIBRASIL/ArquivoTeste.txt".replace("//", "////");			  
		      FileReader arq = new FileReader(nome);
		      BufferedReader lerArq = new BufferedReader(arq);
		      String linha; 
		      String[] campos = new String[50];
		      String url ="jdbc:postgresql://localhost/ATIBRASIL"; 
		      String usuario="postgres"; 
		      String senha = "root"; 	      	      
		      Class.forName("org.postgresql.Driver"); 
			  con = DriverManager.getConnection(url,usuario,senha);
			  con.setAutoCommit(false);
			  stm = con.createStatement();	
		      stm.executeUpdate("delete from DADOS");
		      con.commit();						      
			  int i = 1;
			  String insertTableSQL = "INSERT INTO DADOS VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
			  PreparedStatement preparedStatement = con.prepareStatement(insertTableSQL);		  
		      do {
		        linha = lerArq.readLine();
		        if (linha != null) {
		        	linha = linha.substring(1, linha.length());
		        	int strInicio = 0;	        		
		        	int strFim = linha.indexOf("|");
		        	int j = 1;	      
	        		preparedStatement.setInt(j, i);
	        		j++;
		        	while (strFim >= 0) {
		        		String campo = linha.substring(strInicio, strFim);
		        		preparedStatement.setString( j , campo);
		        		linha = linha.substring(strFim + 1, linha.length());
		        		strFim = linha.indexOf("|");
		        		j++;
					}		
		        	for (int k = j; k <= 41; k++) {
		        		preparedStatement.setString( k , "");
					}
	        		preparedStatement.setInt( 42 , 0);
		        	i++;
		        	final int x = i;
		        	if (i % 10000 == 0) {
			        	  System.out.println(x);
			        	  //con.commit();
		        	}			        		
		        	preparedStatement.executeUpdate();					        	
		        }
		      } while (linha != null);	  
		      con.commit();
		      con.close();
		      arq.close();
			  stm.close();
			  System.out.println(inicio);
			  System.out.println(new Date());	
			  				
		    } catch (IOException | ClassNotFoundException | SQLException e) {
		          System.out.println(e.getMessage());	          
		    } catch (Exception e) {
		          System.out.println(e.getMessage());
		    }	
		    */		                    		          
      }  
    });
 
    final VBox layout =
      VBoxBuilder.create().spacing(8).children(
        VBoxBuilder.create().spacing(5).children(
          HBoxBuilder.create().spacing(10).children(
            runButton,
            statusLabel).build(),
          progressBar
        ).build(),
        peopleView
      ).build();
    layout.setStyle("-fx-background-color: cornsilk; -fx-padding:10; -fx-font-size: 16;");
    Scene scene = new Scene(layout);
    stage.setScene(scene);
    stage.show();
  }
}